package com.hch.web;

import com.hch.service.BlogService;
import com.hch.service.TagService;
import com.hch.service.TypeService;
import com.hch.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable, Model model) {
        //获取分页的数据
        model.addAttribute("page", blogService.listBlog(pageable));
        //top分类的数据(降序排列)
        model.addAttribute("types", typeService.listTypeTop(6));
        //top标签的数据
        model.addAttribute("tags", tagService.listTagTop(10));
        //最新推荐的博客
        model.addAttribute("recommendBlogs", blogService.listRecommendTopBlog(8));

        return "index";
    }

    //搜索方法
    @PostMapping("/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {
        model.addAttribute("page", blogService.listSearchBlog('%' + query + '%', pageable));
        model.addAttribute("query", query);

        return "/search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        //这里直接拿到的是数据库中存储的博客内容，需要使用工具包将markdown语法转化为html标签
        model.addAttribute("blog",blogService.getAndCovertBlog(id));
        return "blog";
    }

    //获取最新的3篇博客放在footer中
    @GetMapping("/footer/newblog")
    public String newblogs(Model model) {
        model.addAttribute("newblogs", blogService.listRecommendTopBlog(3));
        return "_fragments :: newblogList";
    }
}
